package com.voute.View.Activity;

import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.voute.App.App;
import com.voute.Base.BaseActivity;
import com.voute.Model.Bean.FeedCommentEntity;
import com.voute.Model.Bean.SubCommentsBean;
import com.voute.Presenter.ISubCommentsPresenter;
import com.voute.Presenter.Impl.SubCommentsPresenterImpl;
import com.voute.R;
import com.voute.View.Adapter.FeedDetailCommentAdapter;
import com.voute.View.IView.ISubCommentsView;

import java.util.ArrayList;

/**
 * 评论的二级页面
 * Created by liucxu on 2017/1/25.
 */

public class SubCommentsActivity extends BaseActivity implements ISubCommentsView {
    private SwipeRefreshLayout sub_commts_swipe_refresh_layout;
    private ListView content_list;
    private RelativeLayout back_layout;
    private TextView title;
    private ListView header_listView;
    private CheckBox show_positive_radio;
    private CheckBox show_negative_radio;
    private FeedDetailCommentAdapter lasted_adapter;
    private ArrayList<FeedCommentEntity> lasted_entities = new ArrayList<>();
    private ArrayList<FeedCommentEntity> pos_lasted_entities = new ArrayList<>();
    private ArrayList<FeedCommentEntity> neg_lasted_entities = new ArrayList<>();
    //布局采用头部+listview的方式实现
    private LinearLayout headView;
    private FeedDetailCommentAdapter header_adapter;
    private ArrayList<FeedCommentEntity> header_entities = new ArrayList<>();
    private ArrayList<FeedCommentEntity> pos_header_entities = new ArrayList<>();
    private ArrayList<FeedCommentEntity> neg_header_entities = new ArrayList<>();
    private ISubCommentsPresenter presenter;

    private String fid = "";
    private String anchor = "0";
    private boolean stopLoadMore;
    private boolean isLoading;
    private boolean isRefresh = true;

    @Override
    public int getLayoutId() {
        return R.layout.activity_sub_comments;
    }

    @Override
    public void setupView() {
        sub_commts_swipe_refresh_layout = $(R.id.sub_commts_swipe_refresh_layout);
        content_list = $(R.id.content_list);
        lasted_adapter = new FeedDetailCommentAdapter(this, lasted_entities);
        content_list.setAdapter(lasted_adapter);
        back_layout = $(R.id.back_layout);
        title = $(R.id.title);
        back_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                App.GetInstance().finishActivity(SubCommentsActivity.this);
            }
        });
        headView = (LinearLayout) LayoutInflater.from(getApplicationContext()).inflate(R.layout.header_list_view, null);
        header_listView = (ListView) headView.findViewById(R.id.header_list);
        show_positive_radio = (CheckBox) headView.findViewById(R.id.show_positive_radio);
        show_negative_radio = (CheckBox) headView.findViewById(R.id.show_negative_radio);
        header_adapter = new FeedDetailCommentAdapter(this, header_entities);
        //添加头部
        content_list.addHeaderView(headView, null, false);
        header_listView.setAdapter(header_adapter);
        setListViewHeightBasedOnChildren(header_listView);
        presenter = new SubCommentsPresenterImpl(this);

        sub_commts_swipe_refresh_layout.setColorSchemeColors(Color.parseColor("#0f88eb"));
        sub_commts_swipe_refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                setupData();
            }
        });

        show_positive_radio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                if (checked && show_negative_radio.isChecked()) {
                    header_adapter.setDatas(header_entities);
                    setListViewHeightBasedOnChildren(header_listView);
                    lasted_adapter.setDatas(lasted_entities);
//                    setListViewHeightBasedOnChildren(content_list);
                } else if (checked && (!show_negative_radio.isChecked())) {
                    header_adapter.setDatas(pos_header_entities);
                    setListViewHeightBasedOnChildren(header_listView);
                    lasted_adapter.setDatas(pos_lasted_entities);
//                    setListViewHeightBasedOnChildren(content_list);
                } else if ((!checked) && (show_negative_radio.isChecked())) {
                    header_adapter.setDatas(neg_header_entities);
                    setListViewHeightBasedOnChildren(header_listView);
                    lasted_adapter.setDatas(neg_lasted_entities);
//                    setListViewHeightBasedOnChildren(content_list);
                } else {
                    header_adapter.setDatas(new ArrayList<FeedCommentEntity>());
                    setListViewHeightBasedOnChildren(header_listView);
                    lasted_adapter.setDatas(new ArrayList<FeedCommentEntity>());
//                    setListViewHeightBasedOnChildren(content_list);
                }
            }
        });

        show_negative_radio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                if (checked && show_positive_radio.isChecked()) {
                    header_adapter.setDatas(header_entities);
                    setListViewHeightBasedOnChildren(header_listView);
                    lasted_adapter.setDatas(lasted_entities);
//                    setListViewHeightBasedOnChildren(content_list);
                } else if (checked && (!show_positive_radio.isChecked())) {
                    header_adapter.setDatas(neg_header_entities);
                    setListViewHeightBasedOnChildren(header_listView);
                    lasted_adapter.setDatas(neg_lasted_entities);
//                    setListViewHeightBasedOnChildren(content_list);
                } else if ((!checked) && (show_positive_radio.isChecked())) {
                    header_adapter.setDatas(pos_header_entities);
                    setListViewHeightBasedOnChildren(header_listView);
                    lasted_adapter.setDatas(pos_lasted_entities);
//                    setListViewHeightBasedOnChildren(content_list);
                } else {
                    header_adapter.setDatas(new ArrayList<FeedCommentEntity>());
                    setListViewHeightBasedOnChildren(header_listView);
                    lasted_adapter.setDatas(new ArrayList<FeedCommentEntity>());
//                    setListViewHeightBasedOnChildren(content_list);
                }
            }
        });

        content_list.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int last_visiable = absListView.getLastVisiblePosition();
                if (!stopLoadMore && !isLoading && (last_visiable > 0)) {
                    if (last_visiable + 2 > totalItemCount) {
                        isRefresh = false;
                        getPageSubComments(isRefresh);
                    }
                }
            }
        });
    }

    @Override
    public void setupData() {
        Intent intent = getIntent();
        fid = intent.getStringExtra("key_fid");
        if (TextUtils.isEmpty(fid)) {
            App.GetInstance().finishActivity(this);
        } else {
            presenter.getComments(fid, anchor);
        }
    }

    @Override
    public void loadSubComments(SubCommentsBean beans) {
        if (beans != null) {
            if (beans.getStatus() == 0) {
                isLoading = false;
                if (isRefresh) {
                    anchor = "0";
                    lasted_entities.clear();
                    pos_lasted_entities.clear();
                    neg_lasted_entities.clear();
                    header_entities.clear();
                    pos_header_entities.clear();
                    neg_header_entities.clear();
                    isRefresh = false;
                    if (beans.getData() != null) {
                        if (beans.getData().getHot() == null) {
                            header_listView.setVisibility(View.GONE);
                            header_adapter.setDatas(header_entities);
                            setListViewHeightBasedOnChildren(header_listView);
                        } else {
                            header_listView.setVisibility(View.VISIBLE);
                            if (beans.getData().getHot().getNeg() != null) {
                                header_entities.addAll(beans.getData().getHot().getNeg());
                            }
                            if (beans.getData().getHot().getPos() != null) {
                                header_entities.addAll(beans.getData().getHot().getPos());
                            }
                            pos_header_entities.addAll(seperateEntities(header_entities, true));
                            neg_header_entities.addAll(seperateEntities(header_entities, false));
                            header_adapter.setDatas(header_entities);
                            setListViewHeightBasedOnChildren(header_listView);
                        }
                    } else {
                        header_listView.setVisibility(View.GONE);
                    }
                }
                if (beans.getData() != null) {
                    if (beans.getData().getLatest() != null && beans.getData().getLatest().size() > 0) {
                        lasted_entities.addAll(beans.getData().getLatest());
                        ArrayList<FeedCommentEntity> local_pos=new ArrayList<>();
                        local_pos.addAll(pos_lasted_entities);
                        pos_lasted_entities.clear();
                        pos_lasted_entities.addAll(deleteRecountEntity(seperateEntities(lasted_entities, true),local_pos));
                        //去重才行
                        ArrayList<FeedCommentEntity> local_neg=new ArrayList<>();
                        local_neg.addAll(neg_lasted_entities);
                        neg_lasted_entities.clear();
                        neg_lasted_entities.addAll(deleteRecountEntity(seperateEntities(lasted_entities, false),local_neg));
                        if (show_positive_radio.isChecked() && show_negative_radio.isChecked()) {
                            lasted_adapter.setDatas(lasted_entities);
                        } else if (show_positive_radio.isChecked() && (!show_negative_radio.isChecked())) {
                            lasted_adapter.setDatas(pos_lasted_entities);
                        } else if ((!show_positive_radio.isChecked()) && (show_negative_radio.isChecked())) {
                            lasted_adapter.setDatas(neg_lasted_entities);
                        } else {
                            lasted_adapter.setDatas(new ArrayList<FeedCommentEntity>());
                        }
                        stopLoadMore = false;
                    } else {
                        stopLoadMore = true;
                    }
                } else {
                    isLoading = false;
                    stopLoadMore = false;
                }
            } else {
                isLoading = false;
                stopLoadMore = false;
            }
        } else {
            isLoading = false;
            stopLoadMore = false;
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showError(String errMsg) {

    }

    private void getPageSubComments(boolean refresh) {
        String anchor = "0";
        if (refresh)
            anchor = "0";
        else {
            if (lasted_entities.size() == 0) {
                anchor = "0";
            } else {
                anchor = lasted_entities.get(lasted_entities.size() - 1).getCid() + "";
            }
        }
        if (!refresh) {
            if (stopLoadMore) {
                return;
            } else {
                stopLoadMore = true;
                isLoading = true;
            }
        } else {
            isLoading = true;
            stopLoadMore = true;
        }
        presenter.getComments(fid, anchor);
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    private ArrayList<FeedCommentEntity> seperateEntities(ArrayList<FeedCommentEntity> source, boolean is_positive) {
        ArrayList<FeedCommentEntity> out = new ArrayList<>();
        if (source != null) {
            for (FeedCommentEntity entity : source) {
                if (entity.is_pos() == is_positive) {
                    out.add(entity);
                }
            }
        }
        return out;
    }

    private ArrayList<FeedCommentEntity> deleteRecountEntity(ArrayList<FeedCommentEntity> source1, ArrayList<FeedCommentEntity> source2) {
        ArrayList<FeedCommentEntity> entities = new ArrayList<>();
        for (int i = 0; i < source1.size(); i++) {
            boolean contains = false;
            for (int index = 0; index < source2.size(); index++) {
                if (source1.get(i).getCid() == source2.get(index).getCid()) {
                    contains = true;
                }
            }
            if (!contains) {
                entities.add(source1.get(i));
            }
        }
        entities.addAll(source2);
        return entities;
    }
}
